package cn.loioi.web.components.spring;

import java.io.IOException;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import cn.loioi.web.components.spring.result.Result;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :如果返回类型为Result<?>，则视为JSON返回 <br>
 * @file_name :ResultJsonHttpMessageConverter.java <br>
 * @system_name :car-client <br>
 * @author :yyzh <br>
 * @创建时间 :2016年4月16日 下午2:00:09
 */
public class ResultHttpMessageConverter extends AbstractHttpMessageConverter<Result<?>> {

	private static final Charset defaultCharset = Charset.forName("UTF-8");

	public ResultHttpMessageConverter() {
		super(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8, MediaType.ALL);
	}

	@Override
	public boolean canWrite(Class<?> clazz, MediaType mediaType) {
		return Result.class.isAssignableFrom(clazz);
	}

	@Override
	protected Long getContentLength(Result<?> result, MediaType contentType) throws IOException {
		return super.getContentLength(result, contentType);
	}

	@Override
	protected Result<?> readInternal(Class<? extends Result<?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		return null;
	}

	@Override
	protected void writeInternal(Result<?> result, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		StreamUtils.copy(result.toString(), defaultCharset, outputMessage.getBody());
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return false;
	}
}
